#include "AudioManager.h"

AudioManager::AudioManager( ISoundEngine * _soundEngine ){
//AudioManager::AudioManager( ){
	mSoundEngine = _soundEngine;
	//mSoundEngine = createIrrKlangDevice();
	
	mInitialSources = 0;
        mMusic = 0;
	if( mSoundEngine )
	{
		mSoundEngine->setSoundVolume( 1.0f );
		mInitialSources = mSoundEngine->getSoundSourceCount();
	}
	
}


AudioManager::~AudioManager(){
	unloadAllSounds();
	mSoundEngine = 0;
}

void AudioManager::playSFX( const char *_fileName ){
	if( mSoundEngine ) {
		mSoundEngine->play2D( _fileName, false, false, false, ESM_AUTO_DETECT, false );
	}
}

void AudioManager::playMusic( const char *_fileName, bool bln ){
	if( mSoundEngine ){
		stopMusic();
		mMusic = mSoundEngine->play2D( _fileName, bln, false, true, ESM_STREAMING, false );
	}
}

void AudioManager::pauseMusic( ){
	if( mMusic )
		mMusic->setIsPaused( true );
}

void AudioManager::resumeMusic( ){
	if( mMusic && mMusic->getIsPaused() )
		mMusic->setIsPaused( false );
}

void AudioManager::stopMusic( ){
	if( mMusic )
	{
		mMusic->stop();
		mMusic->drop();
		mMusic = 0;
	}
}

void AudioManager::setAudioVolume( irrklang::ik_f32 _volume ){
	if( _volume < 0.0f )
		mSoundEngine->setSoundVolume( 0.0f );
	else if( _volume > 1.0f )
		mSoundEngine->setSoundVolume( 1.0f);
	else
		mSoundEngine->setSoundVolume( _volume );
}

irrklang::ik_f32 AudioManager::getAudioVolume(){
	return mSoundEngine->getSoundVolume();
}

void AudioManager::unloadAllSounds(){
	
	// unload used soudSources if any
	if( mSoundEngine )	{
		irrklang::ik_s32 max = mSoundEngine->getSoundSourceCount();
		for( irrklang::ik_s32 i= max-1; i>=0 && i>mInitialSources-1 ; i-- )
			mSoundEngine->removeSoundSource( mSoundEngine->getSoundSource( i ) );
	}
	
	stopMusic();
}